package cn.adkii.springframework.context.support;

import cn.adkii.springframework.beans.BeansException;
import cn.adkii.springframework.beans.factory.config.BeanPostProcessor;
import cn.adkii.springframework.context.ApplicationContext;
import cn.adkii.springframework.context.ApplicationContextAware;

/**
 * @author malingdi
 * @description 包装处理器
 * @date 2023/11/24 18:36
 */
public class ApplicationContextAwareProcessor implements BeanPostProcessor {

    private final ApplicationContext applicationContext;

    public ApplicationContextAwareProcessor(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    /**
     * 由于ApplicationContext的获取并不能直接在创建Bean时候就可以拿到，所以需要在refresh操作时，把ApplicationContext
     * 写入到一个包装的BeanPostProcessor中去，再去AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization 方法调用 ？？？
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof ApplicationContextAware){
            ((ApplicationContextAware) bean).setApplicationContext(applicationContext);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}
